package com.siha_back.controller;

import com.siha_back.common.AnalysisResult;
import com.siha_back.common.Result;
import com.siha_back.interceptor.OssUtil;
import com.siha_back.service.VideoAnalysisService;
import com.siha_back.utils.ThreadLocalUtil;
import com.siha_back.utils.VideoAnalysisException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@RestController
@RequestMapping("/video")
public class VideoUploadController {
    @Autowired
    private OssUtil ossUtil;

    @Autowired
    private VideoAnalysisService videoAnalysisService;

    /**
     *面试视频上传oss
     *
     **/
    @PostMapping("/upload")
    public String uploadVideo(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空，请选择一个视频文件";
        }

        try {
            String customTempDirPath = "D:/siha";
            Path tempDir = Paths.get(customTempDirPath);
            File tempFile = File.createTempFile("video", file.getOriginalFilename(),tempDir.toFile());
            // 将 MultipartFile 的内容传输到临时文件
            file.transferTo(tempFile);
            Map<String, Object> map = ThreadLocalUtil.get();
            int id = (Integer) map.get("id");
            // 构造OSS对象名称
            String objectName = "videos/" + id+"/"+file.getOriginalFilename();

            // 调用OssUtil上传文件
            String url = ossUtil.uploadFile(tempFile, objectName);

            // 删除临时文件
            tempFile.delete();

            return "视频上传成功" ;
        } catch (IOException e) {
            e.printStackTrace();
            return "视频上传失败：" + e.getMessage();
        }
    }

    /**
     * 微表情分析
     **/
    @PostMapping("/analyse")
    public Result<AnalysisResult> analyseVideo(@RequestParam("file") MultipartFile file) {
        try {
            //视频解析
            AnalysisResult result = videoAnalysisService.analyzeVideo(file);

            return Result.success(result);
        } catch (IOException | VideoAnalysisException e) {
            e.printStackTrace();
            System.out.println("视频上传失败：" + e.getMessage());
            return null;
        }
    }
}
